//
//  XXHomeSearchViewController.m
//  XiuXiuTuanGou
//
//  Created by 王克博 on 2019/5/11.
//  Copyright © 2019 XiuXiuTuanGou. All rights reserved.
//

#import "MeatHotWordViewController.h"
#import "MeatSearchShopViewController.h"
#import "FMTagsView.h"
#import "MeatSearchErrorOrEmptyTableViewCell.h"

@interface MeatHotWordViewController () <UITextFieldDelegate, FMTagsViewDelegate, UIScrollViewDelegate>

@property (strong, nonatomic) UIView * navView;
@property (strong, nonatomic) UITextField *searchTextField;
@property (strong, nonatomic) UIButton *cancelButton;

@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) UILabel *historyTitleLabel;
@property (strong, nonatomic) UIButton *historyDeleteButton;
@property (strong, nonatomic) FMTagsView *historyTagView;      //历史搜索记录

@property (strong, nonatomic) UILabel *hotTitleLabel;
@property (strong, nonatomic) FMTagsView *hotTagView;          //热门搜索

@property (strong, nonatomic) NSMutableArray *dataArray;
@property (strong, nonatomic) NSMutableArray *historyArray;

@property (assign, nonatomic) BOOL isGetDataSuccess; //是否获取数据失败
@property (assign, nonatomic) BOOL isNotNeedSaveHistory;    //是否不需要保存历史搜索记录

@end

@implementation MeatHotWordViewController

#pragma mark - lifecycle methods

- (void)setupUI{
    
    self.view.backgroundColor = KWhiteColor;
    self.baseNavView.hidden = YES;
    
    _dataArray = [NSMutableArray array];
    _historyArray = [NSMutableArray array];
    _isNotNeedSaveHistory = NO;

    [self initArrayData];

    [self.view addSubview:self.navView];
    [self.searchTextField becomeFirstResponder];
    [self.view addSubview:self.scrollView];
    [self.view addSubview:self.tableView];

    [self reloadTagsView];
}

- (void)setupLayout{
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(self.navView.bottom);
    }];
}


#pragma mark - networking methods

- (void)reloadTagsView
{
    float historyViewBottom;
    
    if (self.hotWords.count > 0) {
        self.hotTitleLabel.hidden = NO;
        self.hotTagView.hidden = NO;
        self.hotTagView.tagsArray = self.hotWords;
        self.hotTagView.top = self.hotTitleLabel.bottom+15;
        float height = [self getFMTagViewHeight:self.hotTagView];
        self.hotTagView.height = height;
        historyViewBottom = self.hotTagView.bottom+30;
    }else {
        self.hotTitleLabel.hidden = YES;
        self.hotTagView.hidden = YES;
        historyViewBottom = 30;
    }

    if (self.historyArray.count > 0) {
        self.historyTitleLabel.hidden = NO;
        self.historyDeleteButton.hidden = NO;
        self.historyTagView.hidden = NO;
        self.historyTagView.tagsArray = self.historyArray;
        self.historyTitleLabel.top = historyViewBottom;
        self.historyDeleteButton.mj_y = historyViewBottom;
        self.historyTagView.mj_y = self.historyTitleLabel.bottom + 15;
        self.scrollView.contentSize = CGSizeMake(KScreenWidth, self.historyTagView.bottom+30);

    }else {
        self.historyTitleLabel.hidden = YES;
        self.historyDeleteButton.hidden = YES;
        self.historyTagView.hidden = YES;

        if (self.historyTagView.hidden != YES) {
            self.scrollView.contentSize = CGSizeMake(KScreenWidth, self.historyTagView.bottom+30);
        }else {
            self.scrollView.contentSize = CGSizeMake(KScreenWidth,self.scrollView.height);
        }
    }
}

- (void)initArrayData
{
    //获取缓存的历史记录
    if ([kUserDefaults arrayForKey:kUserSearchHistory]) {
        [_historyArray addObjectsFromArray:[kUserDefaults arrayForKey:kUserSearchHistory]];
    }
}

//- (void)needReloadData
//{
//    _page = 1;
//    XXNetWorking * manager = [XXNetWorking sharedInstance];
//    kWeakSelf(self)
//    if (_dataArray.count > 0) {
//        [_dataArray removeAllObjects];
//    }
//    [manager getHomeDataWithAction:@"0" cid:@"" keyword:_searchTextField.text CallBack:^(BOOL isSucessed, id outParam, NSString *eMsg) {
//        [weakself.tableView.mj_header endRefreshing];
//        if (isSucessed == YES) {
//            weakself.isGetDataSuccess = YES;
//            weakself.model = [XXHomeModel modelWithJSON:outParam];
//            if (weakself.model.data.stores) {
//                [weakself.dataArray addObjectsFromArray:weakself.model.data.stores];
//            }
//            if (weakself.model.data.stores.count < 10) {
//                weakself.tableView.mj_footer = nil;
//            }
//            if (weakself.model.data.stores.count == 10) {
//                if (weakself.tableView.mj_footer == nil) {
//                    [weakself setupFooterRefresh];
//                }
//            }
//        }else {
//            weakself.isGetDataSuccess = NO;
//        }
//        [weakself.tableView reloadData];
//    }];
//}
//
//
//- (void)needReloadMoreData
//{
//    _page++;
//    XXNetWorking * manager = [XXNetWorking sharedInstance];
//    kWeakSelf(self)
//    [manager getHomeMoreDataWithAction:@"0" cid:@"" keyword:_searchTextField.text page:_page CallBack:^(BOOL isSucessed, id outParam, NSString *eMsg) {
//        [weakself.tableView.mj_footer endRefreshing];
//        if (isSucessed == YES) {
//            XXHomeModel * model = [XXHomeModel modelWithJSON:outParam];
//            if (model.data.stores) {
//                [weakself.dataArray addObjectsFromArray:model.data.stores];
//            }
//            if (model.data.stores.count < 10) {
//                weakself.tableView.mj_footer = nil;
//            }
//        }
//        [weakself.tableView reloadData];
//    }];
//}

#pragma mark - FMTagsViewDelegate
- (void)tagsView:(FMTagsView *)tagsView didSelectTagAtIndex:(NSUInteger)index
{
//    if (!self.tableView) {
//        [self.view addSubview:self.tableView];
//    }
//    if (self.tableView.hidden != NO) {
//        self.tableView.hidden = NO;
//    }
//    if (tagsView == self.historyTagView) {
//        if (index < self.historyArray.count) {
//            NSString * keyword = self.historyArray[index];
//            if (keyword) {
//                self.searchTextField.text = keyword;
//               // [self needReloadData];
//            }
//        }
//    }else if (tagsView == self.hotTagView) {
//        if (index < self.hotWords.count) {
//            NSString * keyword = self.hotWords[index];
//            if (keyword) {
//                self.searchTextField.text = keyword;
//                //[self needReloadData];
//            }
//        }
//    }
    
    MeatSearchShopViewController *vc = [[MeatSearchShopViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];

}

#pragma mark - textfield delegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    //如果键盘取消 需要将当前搜索内容当做搜索记录保存
    if (textField == self.searchTextField) {
        if (_isNotNeedSaveHistory != YES) {
            if (self.searchTextField.text.length > 0) {
                if ([kUserDefaults arrayForKey:kUserSearchHistory]) {
                    NSArray * array = [kUserDefaults arrayForKey:kUserSearchHistory];
                    
                    for (NSString *str in array) {
                        if ([str isEqualToString:self.searchTextField.text]) {
                            //判断 当前搜索字段已包含则直接退出 不处理
                            return;
                        }
                    }
                    
                    NSMutableArray * newArray = [NSMutableArray arrayWithArray:array];
                    //如果数组为10条 需要删除1条 再插入一条，限制最多10条
                    if (newArray.count >= 10) {
                        [newArray removeLastObject];
                    }
                    [newArray insertObject:self.searchTextField.text atIndex:0];
                    NSArray * lastArray = [NSArray arrayWithArray:newArray];
                    [kUserDefaults setObject:lastArray forKey:kUserSearchHistory];
                    [kUserDefaults synchronize];
                }else {
                    NSArray * array = [NSArray arrayWithObject:self.searchTextField.text];
                    [kUserDefaults setObject:array forKey:kUserSearchHistory];
                    [kUserDefaults synchronize];
                }
                if (_historyArray.count >= 10) {
                    [_historyArray removeLastObject];
                }
                [_historyArray insertObject:self.searchTextField.text atIndex:0];
                [self reloadTagsView];
            }
        }else {
            _isNotNeedSaveHistory = NO;
        }
    }
}


#pragma mark - tableview.datasource methods

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.searchTextField resignFirstResponder];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_dataArray.count == 0) {
        return 1;
    }
    
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataArray.count == 0) {
        return KScreenHeight-self.navView.bottom -TJ_SafeAreaBottomHeight;
    }
    return 112;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataArray.count == 0) {
        MeatSearchErrorOrEmptyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"MeatSearchErrorOrEmptyTableViewCell"];
//        [cell updataWithIsError:!_isGetDataSuccess emptyMsg:@"未搜索到相关店铺"];
//        kWeakSelf(self)
//        cell.clickReloadButtonBlock = ^{
//            [weakself needReloadData];
//        };
        return cell;
    }
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    return cell;
}


#pragma mark - tableview.delegate methods

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.searchTextField resignFirstResponder];
//    if (indexPath.row < _dataArray.count) {
//        XXHomeStoresModel * model = _dataArray[indexPath.row];
//        kWeakSelf(self)
//        [self dismissViewControllerAnimated:YES completion:^{
//            if (weakself.choosedCellBlock) {
//                weakself.choosedCellBlock(model);
//            }
//        }];
//    }
}


#pragma mark - setter methods
#pragma mark - getter methods

- (UIView *)navView
{
    if (!_navView) {
        _navView = [UIView makeViewBgColor:KWhiteColor cornerRadius:0];
        _navView.frame = CGRectMake(0, TJ_StatusBarHeight_Define, KScreenWidth, 44);
        
        UIView *searchView = [UIView makeViewBgColor:UIColorFromRGB(0xF7F7F7) cornerRadius:17];
        searchView.frame = CGRectMake(15, 3, KScreenWidth-15-58, 34);
        [self addShadowAndCircleCorner:searchView.layer corner:17];
        [_navView addSubview:searchView];

        UIImageView *searchImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 34, 34)];
        searchImgView.image = [UIImage imageNamed:@"meat_buy_search"];
        searchImgView.contentMode = UIViewContentModeCenter;
        [searchView addSubview:searchImgView];

        [searchView addSubview:self.searchTextField];
        [_navView addSubview:self.cancelButton];
        self.cancelButton.centerY = searchView.centerY;
    }
    return _navView;
}


- (UITextField *)searchTextField
{
    if (!_searchTextField) {
        _searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(34, 0, KScreenWidth-15-34-80, 34)];
        _searchTextField.placeholder = @"输入店铺名或者部位进行搜索";
        _searchTextField.delegate = self;
        _searchTextField.textColor = UIColorFromRGB(0xB2B2B2);
        _searchTextField.font = mFont(14);
        _searchTextField.returnKeyType = UIReturnKeySearch;
    }
    return _searchTextField;
}

- (UIButton *)cancelButton
{
    if (!_cancelButton) {
        _cancelButton = [UIButton makeButtonWithText:@"取消" textColor:UIColorFromRGB(0x666666) font:mFont(14) textAliment:1 cornerRadius:0];
        _cancelButton.frame = CGRectMake(KScreenWidth- 58, 0, 58, 44);
        
        @weakify(self);
        _cancelButton.tapBlock = ^{
            @strongify(self);
            self.searchTextField.text = @"";
            [self.searchTextField resignFirstResponder];
            [self.dataArray removeAllObjects];
            self.tableView.hidden = YES;
            [self dismissViewControllerAnimated:YES completion:nil];
        };
    }
    return _cancelButton;
}

- (void)registerTableViewCell
{
     self.tableView.hidden = YES;
    [self.tableView registerClass:[MeatSearchErrorOrEmptyTableViewCell class] forCellReuseIdentifier:@"MeatSearchErrorOrEmptyTableViewCell"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
}

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, self.navView.bottom, KScreenWidth, KScreenHeight-self.navView.bottom -TJ_SafeAreaBottomHeight)];
        _scrollView.delegate = self;
        
        [_scrollView addSubview:self.historyTitleLabel];
        [_scrollView addSubview:self.historyDeleteButton];
        [_scrollView addSubview:self.historyTagView];
        
        [_scrollView addSubview:self.hotTitleLabel];
        [_scrollView addSubview:self.hotTagView];
    }
    return _scrollView;
}

- (UILabel *)hotTitleLabel
{
    if (!_hotTitleLabel) {
        _hotTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 30, 100, 25)];
        _hotTitleLabel.text = @"推荐搜索";
        _hotTitleLabel.textColor = UIColorFromRGB(0x666666);
        _hotTitleLabel.font = mFont(14);
    }
    return _hotTitleLabel;
}


- (FMTagsView *)hotTagView
{
    if (!_hotTagView) {
        _hotTagView  = [[FMTagsView alloc] initWithFrame:CGRectMake(15, self.hotTitleLabel.bottom+15, KScreenWidth - 30, 150)];
        _hotTagView.contentInsets = UIEdgeInsetsZero;
        _hotTagView.tagInsets = UIEdgeInsetsMake(6,15,6,15);
        _hotTagView.tagFont = mFont(12);
        _hotTagView.tagSelectedFont = mFont(12);
        _hotTagView.tagBorderWidth = 1;
        _hotTagView.tagcornerRadius = 14;
        _hotTagView.lineSpacing = 10;
        _hotTagView.interitemSpacing = 10;
        _hotTagView.backgroundColor = KWhiteColor;
        _hotTagView.tagBorderColor = UIColorFromRGB(0xF5F5F5);
        _hotTagView.tagSelectedBorderColor = mMainColor;
        _hotTagView.tagBackgroundColor = mBackgroudColor;
        _hotTagView.tagSelectedBackgroundColor = KWhiteColor;
        _hotTagView.tagTextColor = UIColorFromRGB(0x6F6F6F);
        _hotTagView.tagSelectedTextColor = UIColorFromRGB(0x6F6F6F);
        _hotTagView.delegate = self;
    }
    return _hotTagView;
}


- (UILabel *)historyTitleLabel
{
    if (!_historyTitleLabel) {
        _historyTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, self.hotTagView.bottom + 30, 100, 25)];
        _historyTitleLabel.text = @"搜索历史";
        _historyTitleLabel.textColor = UIColorFromRGB(0x666666);
        _historyTitleLabel.font = mFont(14);
    }
    return _historyTitleLabel;
}

- (UIButton *)historyDeleteButton
{
    if (!_historyDeleteButton) {
        _historyDeleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _historyDeleteButton.frame = CGRectMake(KScreenWidth-50, self.historyTitleLabel.top-5, 50, 35);
        [_historyDeleteButton setImage:[UIImage imageNamed:@"meat_shopcart_cancel"] forState:UIControlStateNormal];
        _historyDeleteButton.isNeedAnimation = YES;
        @weakify(self);
        _historyDeleteButton.tapBlock = ^{
            
            @strongify(self);
            [self showMyAlertWithTitle:@"是否删除搜索记录？" message:nil confirmBtnTitle:@"删除" callBack:^{
                
                if ([kUserDefaults arrayForKey:kUserSearchHistory]) {
                    [kUserDefaults setObject:nil forKey:kUserSearchHistory];
                    [kUserDefaults synchronize];
                    [self.historyArray removeAllObjects];
                    [self reloadTagsView];
                }
            }];
        };
        
    }
    return _historyDeleteButton;
}

- (FMTagsView *)historyTagView
{
    if (!_historyTagView) {
        _historyTagView  = [[FMTagsView alloc] initWithFrame:CGRectMake(15, self.historyTitleLabel.bottom+15, KScreenWidth - 30, 0)];
        _historyTagView.height = KScreenHeight - _historyTagView.mj_y;
        _historyTagView.contentInsets = UIEdgeInsetsZero;
        _historyTagView.tagInsets = UIEdgeInsetsMake(6,15,6,15);
        _historyTagView.tagFont = mFont(12);
        _historyTagView.tagSelectedFont = mFont(12);
        _historyTagView.tagBorderWidth = 1;
        _historyTagView.tagcornerRadius = 14;
        _historyTagView.lineSpacing = 10;
        _historyTagView.interitemSpacing = 10;
        _historyTagView.backgroundColor = KWhiteColor;
        _historyTagView.tagBorderColor = UIColorFromRGB(0xF5F5F5);
        _historyTagView.tagSelectedBorderColor = mMainColor;
        _historyTagView.tagBackgroundColor = mBackgroudColor;
        _historyTagView.tagSelectedBackgroundColor = KWhiteColor;
        _historyTagView.tagTextColor = UIColorFromRGB(0x6F6F6F);
        _historyTagView.tagSelectedTextColor = UIColorFromRGB(0x6F6F6F);
        _historyTagView.delegate = self;
    }
    return _historyTagView;
}



#pragma mark - notifications

- (void)addNotifications{
    
    [kNotificationCenter addObserver:self selector:@selector(textFieldTextDidChanged:) name:UITextFieldTextDidChangeNotification object:self.searchTextField];
}

- (void)removeNotifications{
    [kNotificationCenter removeObserver:self name:UITextFieldTextDidChangeNotification object:self.searchTextField];
}

- (void)textFieldTextDidChanged:(NSNotification *)notification
{
    //输入款内容改变通知
    if (!self.tableView) {
        [self.view addSubview:self.tableView];
        self.tableView.backgroundColor = KRedColor;
    }
    UITextField * textField = notification.object;
    if (textField == self.searchTextField) {
        if (textField.text.length == 0) {
            [_dataArray removeAllObjects];
            [self.tableView reloadData];
            self.tableView.hidden = YES;
        }else {
            self.tableView.hidden = NO;
            // [self needReloadData];
        }
    }
}


@end
